<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>我的订单</title>
  <!--引入的vue.js-->
  <script src="/js/vue.js"></script>
  <!--vue提供的生成二维码的组件-->
  <script src="/js/vue-qriously.js"></script>
  <!--引入elementUI的css-->
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <!--引入elementUI的js-->
  <script src="/js/index.js"></script>
  <!--引入axios.js-->
  <script src="/js/axios.min.js"></script>
  <style>
    /* 基础样式设置 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Helvetica Neue', Arial, sans-serif;
    }

    body {
      background-color: #f8f9fa;
      color: #333;
      line-height: 1.6;
      display: flex;
      flex-direction: column;
      min-height: 100vh;
    }

    a {
      text-decoration: none;
      color: inherit;
    }

    ul {
      list-style: none;
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 15px;
    }

    .btn {
      display: inline-block;
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .btn:hover {
      background-color: #45a049;
    }

    .section-title {
      text-align: center;
      margin-bottom: 30px;
      font-size: 28px;
      color: #2c3e50;
      position: relative;
      padding-bottom: 15px;
    }

    .section-title:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 80px;
      height: 3px;
      background-color: #4CAF50;
    }

    /* 头部样式 */
    header {
      background-color: white;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    .header-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
    }

    .logo {
      font-size: 24px;
      font-weight: bold;
      color: #4CAF50;
    }

    .logo span {
      color: #2c3e50;
    }

    nav ul {
      display: flex;
    }

    nav ul li {
      margin-left: 20px;
    }

    nav ul li a {
      padding: 5px 10px;
      transition: color 0.3s;
    }

    nav ul li a:hover {
      color: #4CAF50;
    }

    .auth-buttons {
      display: flex;
      gap: 10px;
    }

    .auth-buttons .btn {
      padding: 8px 15px;
    }

    .btn-login {
      background-color: transparent;
      color: #4CAF50;
      border: 1px solid #4CAF50;
    }

    .btn-login:hover {
      background-color: #4CAF50;
      color: white;
    }

    /* 订单列表样式 */
    .order-container {
      margin: 20px 0;
    }

    .filter-section {
      background-color: white;
      padding: 15px 20px;
      border-radius: 10px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      margin-bottom: 25px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 15px;
    }

    .filter-tabs {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .filter-tabs .el-button {
      border-radius: 20px;
      border-color: #dcdfe6;
      color: #606266;
    }

    .filter-tabs .el-button.active {
      background-color: #4CAF50;
      border-color: #4CAF50;
      color: white;
    }

    .filter-actions {
      display: flex;
      gap: 10px;
    }

    .order-card {
      background-color: white;
      border-radius: 10px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      padding: 20px;
      margin-bottom: 20px;
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      padding-bottom: 15px;
      margin-bottom: 15px;
    }

    .order-no {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .order-status {
      font-weight: bold;
    }

    .order-content {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
    }

    .order-info {
      flex: 1;
    }

    .info-item {
      margin-bottom: 8px;
      display: flex;
    }

    .info-label {
      width: 80px;
      color: #888;
    }

    .info-content {
      flex: 1;
      color: #666;
    }

    .order-price {
      font-size: 18px;
      color: #f56c6c;
      font-weight: bold;
    }

    .order-footer {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }

    .empty-state {
      text-align: center;
      padding: 40px 20px;
      background-color: white;
      border-radius: 10px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }

    .empty-state i {
      font-size: 48px;
      color: #c0c4cc;
      margin-bottom: 15px;
    }

    .empty-state p {
      color: #909399;
      font-size: 16px;
    }

    /* 详情弹窗样式 */
    .detail-dialog .el-dialog__body {
      padding: 20px;
    }

    .detail-section {
      margin-bottom: 20px;
    }

    .detail-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }

    .detail-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 15px;
    }

    .detail-item {
      margin-bottom: 10px;
    }

    .detail-label {
      font-weight: bold;
      color: #666;
      margin-right: 10px;
    }

    .detail-content {
      color: #333;
    }

    /* 页脚样式 */
    footer {
      background-color: #2c3e50;
      color: white;
      padding: 20px 0;
      margin-top: auto; /* 关键属性，使页脚始终位于底部 */
      flex-shrink: 0;
    }

    .footer-content {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 30px;
      margin-bottom: 20px;
    }

    .footer-column h3 {
      margin-bottom: 15px;
      font-size: 18px;
    }

    .footer-column ul li {
      margin-bottom: 10px;
    }

    .footer-column ul li a:hover {
      color: #4CAF50;
    }

    .social-icons {
      display: flex;
      gap: 15px;
      margin-top: 15px;
    }

    .social-icons a {
      display: inline-block;
      width: 40px;
      height: 40px;
      background-color: rgba(255, 255, 255, 0.1);
      border-radius: 50%;
      text-align: center;
      line-height: 40px;
      transition: background-color 0.3s;
    }

    .social-icons a:hover {
      background-color: #4CAF50;
    }

    .copyright {
      text-align: center;
      padding-top: 20px;
      border-top: 1px solid rgba(255, 255, 255, 0.1);
      font-size: 14px;
    }

    /* 支付弹窗样式 */
    .qr-container {
      text-align: center;
      padding: 20px;
    }

    .qr-code {
      width: 200px;
      height: 200px;
      margin: 0 auto 20px;
    }

    .countdown {
      font-size: 18px;
      color: #f56c6c;
      margin: 10px 0;
    }

    /* 退款记录样式 */
    .refund-history {
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #eee;
    }

    .refund-item {
      padding: 10px;
      border-bottom: 1px solid #eee;
    }

    .refund-item:last-child {
      border-bottom: none;
    }

    .refund-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;
    }

    .refund-amount {
      font-weight: bold;
      color: #f56c6c;
    }

    .refund-status {
      font-weight: bold;
    }

    .refund-time {
      color: #999;
      font-size: 12px;
    }

    .refund-reason {
      color: #666;
      font-size: 14px;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .header-container {
        flex-direction: column;
        gap: 15px;
      }

      nav ul {
        flex-wrap: wrap;
        justify-content: center;
      }

      nav ul li {
        margin: 5px 10px;
      }

      .order-content {
        flex-direction: column;
      }

      .detail-grid {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
<!-- 头部导航 -->
<header>
  <div class="container header-container">
    <div class="logo">
      <a href="index.html">探索<span>世界</span></a>
    </div>
    <nav>
      <ul>
        <li><a href="index.html">首页</a></li>
        <li><a href="scenic.html">景区</a></li>
        <li><a href="dot.html">景点</a></li>
        <li><a href="order.html"style="color: #4CAF50; font-weight: bold;" >订单</a></li>
        <li><a href="guide.html">攻略</a></li>
        <li><a href="notes.html">游记</a></li>
      </ul>
    </nav>
    <div class="auth-buttons" id="authButtons">
      <!-- 登录状态由JavaScript动态生成 -->
    </div>
  </div>
</header>

<div class="container main-content">
  <h1 class="page-title">我的订单</h1>

  <div id="app">
    <div class="order-container">
      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="filter-tabs">
          <el-button 
            v-for="tab in statusTabs" 
            :key="tab.value"
            :class="{ 'active': filter.orderState === tab.value }"
            @click="filterByStatus(tab.value)"
            size="medium"
            plain>
            {{ tab.label }}
          </el-button>
        </div>
        <div class="filter-actions">
          <el-button type="primary" @click="loadOrders" icon="el-icon-refresh">刷新订单</el-button>
        </div>
      </div>

      <!-- 订单列表 -->
      <div v-if="orders.length > 0">
        <div class="order-card" v-for="order in orders" :key="order.orderId">
          <div class="order-header">
            <div class="order-no">订单号：{{ order.orderNo }}</div>
            <el-tag :type="getStatusType(order.orderState)">
              {{ getStatusText(order.orderState) }}
            </el-tag>
          </div>
          <div class="order-content">
            <div class="order-info">
              <div class="info-item">
                <span class="info-label">下单时间：</span>
                <span class="info-content">{{ formatDateTime(order.orderTime) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">游玩日期：</span>
                <span class="info-content">{{ formatDate(order.orderYwrq) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">取票人：</span>
                <span class="info-content">{{ order.orderQpname }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">联系电话：</span>
                <span class="info-content">{{ order.orderQprsj }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">门票数量：</span>
                <span class="info-content">{{ order.orderCount }} 张</span>
              </div>
              <!-- 显示待付款订单的支付剩余时间 -->
              <div class="info-item" v-if="order.orderState === '11' && order.orderTime">
                <span class="info-label">支付剩余：</span>
                <span class="info-content">{{ getPaymentRemainingTime(order.orderTime) }}</span>
              </div>
            </div>
            <div class="order-price">￥{{ order.orderTprice }}</div>
          </div>
          <div class="order-footer">
            <el-button size="mini" @click="viewOrderDetail(order)">查看详情</el-button>
            <el-button 
              v-if="order.orderState === '11'" 
              type="success" 
              size="mini" 
              @click="handlePay(order)">
              去支付
            </el-button>
            <el-button 
              v-if="['11'].includes(order.orderState)" 
              type="danger" 
              size="mini" 
              @click="cancelOrder(order)">
              取消订单
            </el-button>
            <el-button 
              v-if="['12', '13'].includes(order.orderState)" 
              type="primary" 
              size="mini" 
              @click="showVerificationCode(order)">
              查看票码
            </el-button>
            <el-button 
              v-if="order.orderState === '12'" 
              type="warning" 
              size="mini" 
              @click="applyRefund(order)">
              申请退款
            </el-button>
          </div>
        </div>
      </div>

      <!-- 无订单提示 -->
      <div v-else class="empty-state">
        <i class="el-icon-document"></i>
        <p>暂无订单信息</p>
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="showDetailDialog"
      width="60%"
      class="detail-dialog">
      <div v-if="selectedOrder">
        <div class="detail-section">
          <div class="detail-title">订单信息</div>
          <div class="detail-grid">
            <div>
              <div class="detail-item">
                <span class="detail-label">订单号：</span>
                <span class="detail-content">{{ selectedOrder.orderNo }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">下单时间：</span>
                <span class="detail-content">{{ formatDateTime(selectedOrder.orderTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">支付时间：</span>
                <span class="detail-content">{{ selectedOrder.payTime ? formatDateTime(selectedOrder.payTime) : (selectedOrder.orderState === '12' ? '已支付但未记录时间' : '未支付') }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">游玩日期：</span>
                <span class="detail-content">{{ formatDate(selectedOrder.orderYwrq) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">支付方式：</span>
                <span class="detail-content">{{ selectedOrder.orderPtype === '1' ? '景区支付' : '在线支付' }}</span>
              </div>
            </div>
            <div>
              <div class="detail-item">
                <span class="detail-label">取票人：</span>
                <span class="detail-content">{{ selectedOrder.orderQpname }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">联系电话：</span>
                <span class="detail-content">{{ selectedOrder.orderQprsj }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">门票数量：</span>
                <span class="detail-content">{{ selectedOrder.orderCount }} 张</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">订单金额：</span>
                <span class="detail-content">￥{{ selectedOrder.orderTprice }}</span>
              </div>
            </div>
            <div>
              <div class="detail-item">
                <span class="detail-label">订单状态：</span>
                <el-tag :type="getStatusType(selectedOrder.orderState)">
                  {{ getStatusText(selectedOrder.orderState) }}
                </el-tag>
              </div>
              <!-- 显示待付款订单的支付剩余时间 -->
              <div class="detail-item" v-if="selectedOrder.orderState === '11' && selectedOrder.orderTime">
                <span class="detail-label">支付剩余：</span>
                <span class="detail-content">{{ getPaymentRemainingTime(selectedOrder.orderTime) }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-section" v-if="selectedOrder.orderItemList && selectedOrder.orderItemList.length > 0">
          <div class="detail-title">门票信息</div>
          <el-table :data="selectedOrder.orderItemList" border stripe>
            <el-table-column label="景区名称" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.ticket && scope.row.ticket.scenic && scope.row.ticket.scenic.scenicName">
                  {{ scope.row.ticket.scenic.scenicName }}
                </span>
                <span v-else-if="scope.row.ticket && scope.row.ticket.scenicName">
                  {{ scope.row.ticket.scenicName }}
                </span>
                <span v-else-if="scope.row.scenic && scope.row.scenic.scenicName">
                  {{ scope.row.scenic.scenicName }}
                </span>
                <span v-else>
                  {{ scope.row.scenicName || '未知景区' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="ticket.ticketName" label="门票名称" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.ticket">
                  {{ scope.row.ticket.ticketName }}
                </span>
                <span v-else>
                  {{ scope.row.ticketName || '未知门票' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template slot-scope="scope">￥{{ scope.row.unitPrice }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
            <el-table-column label="小计" width="100">
              <template slot-scope="scope">￥{{ (scope.row.unitPrice * scope.row.quantity).toFixed(2) }}</template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 取票验证码（仅在订单已付款或已取票时显示） -->
        <div class="detail-section" v-if="selectedOrder && ['12', '13'].includes(selectedOrder.orderState)">
          <div class="detail-title">取票信息</div>
          <div style="padding: 15px; background-color: #f0f9eb; border: 1px solid #e1f3d8; border-radius: 4px;">
            <div style="display: flex; align-items: center; margin-bottom: 10px;">
              <i class="el-icon-warning" style="color: #67c23a; font-size: 20px; margin-right: 10px;"></i>
              <span style="font-weight: bold; color: #67c23a;">取票验证码</span>
            </div>
            <div v-if="selectedOrder.ticketVerificationCode" style="font-size: 24px; font-weight: bold; text-align: center; color: #333; letter-spacing: 2px;">
              {{ selectedOrder.ticketVerificationCode }}
            </div>
            <div v-else style="text-align: center; color: #f56c6c; font-weight: bold;">
              验证码生成中，请稍后...
            </div>
            <div style="text-align: center; margin-top: 10px; color: #999; font-size: 14px;">
              请在景区取票时向工作人员出示此验证码
            </div>
          </div>
        </div>

        <!-- 退款记录 -->
        <div class="detail-section" v-if="refundHistory && refundHistory.length > 0">
          <div class="detail-title">退款记录</div>
          <div class="refund-history">
            <div class="refund-item" v-for="(refund, index) in refundHistory" :key="index">
              <div class="refund-header">
                <span class="refund-amount">退款金额：￥{{ refund.refundIje }}</span>
                <el-tag :type="getRefundStatusType(refund.refundResult)" size="mini">
                  {{ getRefundStatusText(refund.refundResult) }}
                </el-tag>
              </div>
              <div class="refund-time">{{ formatDateTime(refund.refundTime) }}</div>
              <div class="refund-reason">{{ refund.refundFullmsg }}</div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDetailDialog = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 支付弹窗 -->
    <el-dialog
      title="订单支付"
      :visible.sync="showPaymentDialog"
      width="400px">
      <div v-if="currentPayingOrder" class="qr-container">
        <div style="margin-bottom:10px;">支付金额：￥{{ currentPayingOrder.orderTprice }}</div>
        <div style="margin-bottom:10px;">订单号：{{ currentPayingOrder.orderNo }}</div>
        <div style="margin-bottom:10px;">支付状态：{{ payStatus }}</div>
        <!-- 使用vue-qriously组件生成二维码 -->
        <qriously v-if="code_url" :value="code_url" :size="200" />
        <div class="countdown" v-if="countdown > 0">
          支付剩余时间：{{ Math.floor(countdown/60) }}:{{ (countdown%60).toString().padStart(2,'0') }}
        </div>
        <el-button @click="checkPaymentStatus" :loading="checkingStatus">刷新支付状态</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPaymentDialog = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 退款申请弹窗 -->
    <el-dialog
      title="申请退款"
      :visible.sync="showRefundDialog"
      width="400px">
      <div v-if="currentRefundOrder">
        <el-form :model="refundForm" :rules="refundRules" ref="refundForm" label-width="100px">
          <el-form-item label="订单号：">
            <span>{{ currentRefundOrder.orderNo }}</span>
          </el-form-item>
          <el-form-item label="订单金额：">
            <span>￥{{ currentRefundOrder.orderTprice }}</span>
          </el-form-item>
          <el-form-item label="可退金额：">
            <span>￥{{ availableRefundAmount }}</span>
          </el-form-item>
          <el-form-item label="退款金额：" prop="refundIje">
            <el-input v-model.number="refundForm.refundIje" type="number" :min="0.01" :max="availableRefundAmount">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="退款原因：" prop="refundReason">
            <el-input v-model="refundForm.refundReason" type="textarea" :rows="3" placeholder="请输入退款原因"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRefundDialog = false">取消</el-button>
        <el-button type="primary" @click="submitRefund">提交申请</el-button>
      </span>
    </el-dialog>

    <!-- 取票验证码弹窗 -->
    <el-dialog
      title="取票验证码"
      :visible.sync="showVerificationCodeDialog"
      width="400px">
      <div v-if="currentVerificationOrder" style="text-align: center; padding: 20px;">
        <div style="margin-bottom: 15px; font-size: 16px; color: #666;">请在景区取票时向工作人员出示此验证码</div>
        <div style="font-size: 32px; font-weight: bold; color: #333; letter-spacing: 5px; padding: 20px; background-color: #f5f5f5; border-radius: 8px;">
          {{ currentVerificationOrder.ticketVerificationCode }}
        </div>
        <div style="margin-top: 15px; font-size: 14px; color: #999;">
          订单号：{{ currentVerificationOrder.orderNo }}
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showVerificationCodeDialog = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</div>

<script>
  // 日期格式化函数
  function formatDate(date) {
    if (!date) return '';
    const d = new Date(date);
    let month = '' + (d.getMonth() + 1);
    let day = '' + d.getDate();
    const year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    return [year, month, day].join('-');
  }

  // 日期时间格式化函数，将ISO 8601格式转换为"YYYY-MM-DD HH:mm:ss"
  function formatDateTime(dateTime) {
    if (!dateTime) return '';
    try {
      // 创建Date对象
      const date = new Date(dateTime);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateTime; // 如果无效，返回原始值
      }
      
      // 获取年月日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      
      // 获取时分秒
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      // 返回格式化后的字符串
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return dateTime; // 出错时返回原始值
    }
  }

  // 生成唯一订单号（规则：YYYYMMDDHHMMSS + 6位随机数）
  function generateOrderNo() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
    return `${year}${month}${day}${hours}${minutes}${seconds}${random}`;
  }

  new Vue({
    el: '#app',
    data() {
      return {
        orders: [],
        selectedOrder: null,
        showDetailDialog: false,
        showPaymentDialog: false,
        showRefundDialog: false,
        // 新增取票验证码相关数据
        showVerificationCodeDialog: false,
        currentVerificationOrder: null,
        currentPayingOrder: null,
        currentRefundOrder: null,
        payStatus: '',
        countdown: 0,
        countdownTimer: null,
        statusTimer: null,
        checkingStatus: false,
        qrCodeInstance: null,
        filter: {
          orderState: ''
        },
        refundForm: {
          refundIje: 0,
          refundReason: ''
        },
        refundHistory: [], // 退款历史记录
        refundRules: {
          refundIje: [
            { required: true, message: '请输入退款金额', trigger: 'blur' },
            { type: 'number', min: 0.01, message: '退款金额必须大于0', trigger: 'blur' },
            { 
              validator: (rule, value, callback) => {
                if (value > this.availableRefundAmount) {
                  callback(new Error('退款金额不能超过可退金额'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ],
          refundReason: [
            { required: true, message: '请输入退款原因', trigger: 'blur' }
          ]
        },
        statusTabs: [
          { label: '全部订单', value: '' },
          { label: '待付款', value: '11' },
          { label: '待消费', value: '12' },
          { label: '已取票', value: '13' },
          { label: '退款/售后', value: '14,15,20,22,23,24,26' }
        ]
      };
    },
    computed: {
      // 计算可退金额（订单总金额 - 已退金额）
      availableRefundAmount() {
        if (!this.currentRefundOrder) return 0;
        
        // 在实际应用中，应该从后端获取已退金额
        // 这里简化处理，假设没有退款记录
        return this.currentRefundOrder.orderTprice;
      }
    },
    mounted() {
      this.loadOrders();
    },
    beforeDestroy() {
      // 清理定时器
      if (this.countdownTimer) clearInterval(this.countdownTimer);
      if (this.statusTimer) clearInterval(this.statusTimer);
    },
    methods: {
      // 计算待付款订单的支付剩余时间
      getPaymentRemainingTime(orderTime) {
        // 将订单时间字符串转换为Date对象
        const orderDate = new Date(orderTime);
        // 计算2分钟后的时间（订单超时时间）
        const expireTime = new Date(orderDate.getTime() + 2 * 60 * 1000);
        // 获取当前时间
        const now = new Date();
        // 计算剩余时间（毫秒）
        const remainingTime = expireTime.getTime() - now.getTime();
        
        // 如果已超时，返回提示
        if (remainingTime <= 0) {
          return '已超时';
        }
        
        // 计算剩余分钟和秒数
        const totalSeconds = Math.floor(remainingTime / 1000);
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        
        // 格式化显示
        return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      },
      
      // 格式化日期的函数
      formatDate(date) {
        if (!date) return '';
        const d = new Date(date);
        let month = '' + (d.getMonth() + 1);
        let day = '' + d.getDate();
        const year = d.getFullYear();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        return [year, month, day].join('-');
      },
      // 格式化日期时间的函数
      formatDateTime(dateTime) {
        if (!dateTime) return '';
        try {
          // 创建Date对象
          const date = new Date(dateTime);
          
          // 检查日期是否有效
          if (isNaN(date.getTime())) {
            return dateTime; // 如果无效，返回原始值
          }
          
          // 获取年月日
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          
          // 获取时分秒
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          
          // 返回格式化后的字符串
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        } catch (error) {
          console.error('时间格式化错误:', error);
          return dateTime; // 出错时返回原始值
        }
      },

      // 加载订单列表
      loadOrders() {
        // 从localStorage获取当前登录用户的ID
        const currentUser = JSON.parse(localStorage.getItem('userInfo'));
        const visitorId = currentUser ? currentUser.visitorId : null;
        
        if (!visitorId) {
          this.$message.error('未找到用户信息，请重新登录');
          return;
        }
        
        // 根据游客ID查询订单
        axios.post('/order/queryByVisitorId', null, {
          params: {
            visitorId: visitorId
          }
        })
        .then(response => {
          if (response.data.code === 200) {
            this.orders = response.data.data;
            // 根据筛选条件过滤订单
            if (this.filter.orderState) {
              // 处理多个状态值的情况（如退款/售后）
              if (this.filter.orderState.includes(',')) {
                const states = this.filter.orderState.split(',');
                this.orders = this.orders.filter(order => states.includes(order.orderState));
              } else {
                this.orders = this.orders.filter(order => order.orderState === this.filter.orderState);
              }
            }
            // 检查当前支付的订单是否在列表中，并且已经支付成功
            if (this.currentPayingOrder) {
              const updatedOrder = this.orders.find(order => order.orderId === this.currentPayingOrder.orderId);
              if (updatedOrder && updatedOrder.orderState !== this.currentPayingOrder.orderState && updatedOrder.orderState === '12') {
                // 只有当订单状态变为已付款时才显示成功消息
                // 订单状态已更新，清理定时器
                if (this.countdownTimer) clearInterval(this.countdownTimer);
                if (this.statusTimer) clearInterval(this.statusTimer);
                this.countdownTimer = null;
                this.statusTimer = null;
                this.showPaymentDialog = false;
                this.$message.success('支付成功！');
                // 清除当前支付订单引用，避免重复提示
                this.currentPayingOrder = null;
              }
            }
          } else {
            this.$message.error(response.data.message || '获取订单列表失败');
          }
        })
        .catch(error => {
          this.$message.error('请求失败: ' + error.message);
        });
      },

      // 筛选订单
      filterOrders() {
        this.loadOrders();
      },

      // 按状态筛选订单
      filterByStatus(status) {
        this.filter.orderState = status;
        this.loadOrders();
      },

      // 查看订单详情
      viewOrderDetail(order) {
        this.selectedOrder = order;
        // 加载退款历史记录
        this.loadRefundHistory(order.orderNo);
        this.showDetailDialog = true;
      },
      
      // 显示取票验证码
      showVerificationCode(order) {
        // 确保 order 对象包含 ticketVerificationCode 字段
        if (order && order.ticketVerificationCode) {
          this.currentVerificationOrder = order;
          this.showVerificationCodeDialog = true;
        } else {














          // 如果没有验证码，提示用户
          this.$message.warning('该订单暂无取票验证码，请联系客服');
        }
      },

      // 加载退款历史记录
      loadRefundHistory(orderNo) {
        axios.post('/refund/queryByPage', {
          pageNo: 1,
          pageSize: 100,
          data: {
            orderNo: orderNo
          }
        })
        .then(response => {
          if (response.data.code === 200) {
            this.refundHistory = response.data.data.list || [];
          } else {
            this.$message.error(response.data.message || '获取退款记录失败');
            this.refundHistory = [];
          }
        })
        .catch(error => {
          this.$message.error('请求失败: ' + error.message);
          this.refundHistory = [];
        });
      },

      // 获取状态类型
      getStatusType(state) {
        const map = {
          '11': 'warning',  // 待付款
          '12': 'success',  // 已付款
          '13': 'info',     // 已取票
          '14': 'warning',  // 待审核
          '15': 'warning',  // 待退款
          '20': 'danger',   // 待付款退单结束
          '21': 'danger',   // 付款超时结束
          '22': 'danger',   // 预订成功退单结束
          '23': 'danger',   // 退款已驳回
          '24': 'success',  // 退款成功
          '25': 'danger',   // 取票超时结束
          '26': 'danger',   // 退票结束
          '27': 'danger',   // 点评超时结束
          '28': 'success'   // 点评完成结束
        };
        return map[state] || 'info';
      },

      // 获取状态文本
      getStatusText(state) {
        const map = {
          '11': '待付款',
          '12': '预订成功',
          '13': '已取票',
          '14': '待审核',
          '15': '待退款',
          '20': '待付款退单结束',
          '21': '付款超时结束',
          '22': '预订成功退单结束',
          '23': '退款已驳回',
          '24': '退款成功',
          '25': '取票超时结束',
          '26': '退票结束',
          '27': '点评超时结束',
          '28': '点评完成结束'
        };
        return map[state] || '未知状态';
      },

      // 获取退款状态类型
      getRefundStatusType(status) {
        const map = {
          '0': 'warning',  // 未完成（处理中）
          '1': 'success',  // 已退款（成功）
          '2': 'danger'    // 已驳回（失败）
        };
        return map[status] || 'info';
      },

      // 获取退款状态文本
      getRefundStatusText(status) {
        const map = {
          '0': '未完成',
          '1': '已退款',
          '2': '已驳回'
        };
        return map[status] || '未知状态';
      },

      // 去支付
      handlePay(order) {
        this.currentPayingOrder = order;
        this.showPaymentDialog = true;
        // 只有在倒计时未启动时才创建支付
        if (!this.countdownTimer) {
          this.createPayment(order);
        }
      },

      // 创建支付
      createPayment(order) {
        const payData = {
          orderNo: order.orderNo,
          payPje: order.orderTprice,
          payFullmsg: '景区门票订单支付'
        };

        axios.post('/pay/createNative', payData)
          .then(res => {
            if (res.data.code === 200) {
              const codeUrl = res.data.data.code_url;
              this.code_url = codeUrl; // 保存code_url用于生成二维码
              this.payStatus = '等待支付，请扫码';
              this.showPaymentDialog = true; // 显示对话框
              
              // 只有在倒计时未启动时才启动倒计时和轮询
              if (!this.countdownTimer) {
                this.startCountdown();
                this.startStatusPolling();
              }
            } else {
              this.$message.error(res.data.message || '创建支付失败');
              this.showPaymentDialog = false;
            }
          })
          .catch(err => {
            this.$message.error('创建支付失败：' + err.message);
            this.showPaymentDialog = false;
          });
      },

      // 生成二维码
      generateQRCode(codeUrl) {
        // 清空之前的二维码
        const qrCodeContainer = document.getElementById('qrcode');
        qrCodeContainer.innerHTML = '';
        
        // 生成新二维码
        this.qrCodeInstance = new QRCode(qrCodeContainer, {
          text: codeUrl,
          width: 200,
          height: 200,
          correctLevel: QRCode.CorrectLevel.M
        });
      },

      // 开始倒计时
      startCountdown() {
        // 只有在倒计时未启动时才设置初始值
        if (!this.countdownTimer) {
          this.countdown = 2 * 60; // 2分钟
          this.countdownTimer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer);
              this.countdownTimer = null;
              this.$message.warning('支付超时，订单已自动取消');
              this.showPaymentDialog = false;
              // 自动更新订单状态为支付超时结束(21)
              if (this.currentPayingOrder) {
                axios.post('/order/updateStateByNo', null, {
                  params: {
                    orderNo: this.currentPayingOrder.orderNo,
                    orderState: '21' // CANCEL_PAY_TIMEOUT 状态码
                  }
                }).then(response => {
                  if (response.data.code === 200) {
                    console.log('订单状态已更新为支付超时结束');
                  } else {
                    console.error('更新订单状态失败: ' + (response.data.message || '未知错误'));
                  }
                  // 刷新订单列表
                  this.loadOrders();
                }).catch(error => {
                  console.error('更新订单状态出错: ' + error.message);
                  // 即使更新失败也刷新订单列表
                  this.loadOrders();
                });
              }
            }
          }, 1000);
        }
      },

      // 开始状态轮询
      startStatusPolling() {
        // 只有在轮询未启动时才启动
        if (!this.statusTimer) {
          this.statusTimer = setInterval(() => {
            this.checkPaymentStatus();
          }, 3000); // 每3秒查询一次
        }
      },

      // 查询支付状态
      checkPaymentStatus() {
        // 如果没有正在支付的订单，停止轮询
        if (!this.currentPayingOrder) {
          if (this.statusTimer) {
            clearInterval(this.statusTimer);
            this.statusTimer = null;
          }
          return;
        }
        
        this.checkingStatus = true;
        axios.get(`/pay/queryStatus/${this.currentPayingOrder.orderNo}`)
          .then(res => {
            if (res.data.code === 200) {
              const status = res.data.data;
              if (status === 'SUCCESS') {
                this.payStatus = '支付成功';
                // 清理定时器
                if (this.countdownTimer) clearInterval(this.countdownTimer);
                if (this.statusTimer) clearInterval(this.statusTimer);
                this.countdownTimer = null;
                this.statusTimer = null;
                // 更新订单状态
                this.loadOrders();
                // 注意：不在这里显示成功消息，而是在loadOrders中检查状态变化时显示
                setTimeout(() => {
                  this.showPaymentDialog = false;
                }, 1500);
              } else {
                const statusMap = {
                  'NOTPAY': '等待支付，请扫码',
                  'USERPAYING': '用户支付中',
                  'CLOSED': '支付已关闭',
                  'PAYERROR': '支付失败'
                };
                this.payStatus = statusMap[status] || '未知状态';
              }
            }
          })
          .catch(err => {
            console.error('查询支付状态失败：', err);
          })
          .finally(() => {
            this.checkingStatus = false;
          });
      },

      // 取消订单
      cancelOrder(order) {
        this.$confirm('确定要取消该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用后台接口更新订单状态为"待付款退单结束"(20)
          axios.post('/order/updateStateByNo', null, {
            params: {
              orderNo: order.orderNo,
              orderState: '20' // CANCEL_WAIT_PAY 状态码
            }
          }).then(response => {
            if (response.data.code === 200) {
              this.$message.success('订单已取消');
              // 更新本地订单状态
              order.orderState = '20';
              // 如果详情弹窗中显示的是这个订单，也需要更新详情中的状态
              if (this.selectedOrder && this.selectedOrder.orderNo === order.orderNo) {
                this.selectedOrder.orderState = '20';
              }
              // 重新加载订单列表以确保状态同步
              this.loadOrders();
            } else {
              this.$message.error(response.data.message || '取消订单失败');
            }
          }).catch(error => {
            this.$message.error('取消订单失败: ' + error.message);
          });
        }).catch(() => {
          // 用户点击取消
        });
      },

      // 申请退款
      applyRefund(order) {
        this.currentRefundOrder = order;
        this.refundForm.refundIje = order.orderTprice;
        this.refundForm.refundReason = '';
        this.showRefundDialog = true;
      },

      // 提交退款申请
      submitRefund() {
        this.$refs.refundForm.validate(valid => {
          if (valid) {
            // 构造退款参数
            const refundParam = {
              orderNo: this.currentRefundOrder.orderNo,
              refundIje: this.refundForm.refundIje,
              refundFullmsg: this.refundForm.refundReason || '无'
            };

            axios.post('/refund/insert', refundParam)
                    .then(response => {
                      if (response.data.code === 200) {
                        // 更新订单状态为"待审核"(14)
                        axios.post('/order/updateStateByNo', null, {
                          params: {
                            orderNo: this.currentRefundOrder.orderNo,
                            orderState: '14' // 待审核
                          }
                        })
                                .then(stateResponse => {
                                  if (stateResponse.data.code === 200) {
                                    this.$message.success('退款申请提交成功，等待审核');
                                    this.showRefundDialog = false;
                                    this.loadOrders(); // 刷新订单列表
                                  } else {
                                    this.$message.error('退款申请提交成功，但订单状态更新失败: ' + (stateResponse.data.message || '未知错误'));
                                    this.showRefundDialog = false;
                                    this.loadOrders(); // 仍然刷新订单列表
                                  }
                                })
                                .catch(error => {
                                  this.$message.error('退款申请提交成功，但订单状态更新失败: ' + error.message);
                                  this.showRefundDialog = false;
                                  this.loadOrders(); // 仍然刷新订单列表
                                });
                      } else {
                        this.$message.error('退款申请失败: ' + (response.data.message || '未知错误'));
                      }
                    })
                    .catch(error => {
                      console.error('退款申请出错: ', error);
                      this.$message.error('网络错误，无法提交退款申请');
                    });
          } else {
            this.$message.warning('请完善退款信息');
            return false;
          }
        });
      },

      // 显示取票验证码
      showVerificationCode(order) {
        // 确保 order 对象包含 ticketVerificationCode 字段
        if (order && order.ticketVerificationCode) {
          this.currentVerificationOrder = order;
          this.showVerificationCodeDialog = true;
        } else {
          // 如果没有验证码，提示用户
          this.$message.warning('该订单暂无取票验证码，请联系客服');
        }
      }
    }
  });
  // 检查登录状态并更新导航栏
  function updateAuthButtons() {
    const authButtons = document.getElementById('authButtons');
    const cid = localStorage.getItem('cid');
    const userInfoStr = localStorage.getItem('userInfo');

    if (cid && userInfoStr) {
      // 用户已登录，显示个人中心和退出登录
      try {
        const userInfo = JSON.parse(userInfoStr);
        authButtons.innerHTML = `
                  <span style="margin-right: 15px; color: #4CAF50;">欢迎，${userInfo.visitorsName || userInfo.realName || '用户'}</span>
                  <a href="profile.html" class="btn">个人中心</a>
                  <a href="#" class="btn btn-login" onclick="logout()">退出登录</a>
              `;
      } catch (e) {
        // 解析用户信息失败，显示默认登录状态
        authButtons.innerHTML = `
                  <a href="login.html" class="btn btn-login">登录</a>
                  <a href="register.html" class="btn">注册</a>
              `;
      }
    } else {
      // 用户未登录，显示登录注册按钮
      authButtons.innerHTML = `
              <a href="login.html" class="btn btn-login">登录</a>
              <a href="register.html" class="btn">注册</a>
          `;
    }
  }

  // 通用的退出登录函数（用于导航栏）
  function logout() {
    if (confirm('确定要退出登录吗？')) {
      // 清除本地存储的用户信息
      localStorage.removeItem('cid');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');

      // 更新导航栏显示
      updateAuthButtons();

      // 延迟跳转到首页
      setTimeout(() => {
        window.location.href = 'index.html';
      }, 500);
    }
    return false; // 阻止链接默认行为
  }

  // 页面加载时更新导航栏状态
  document.addEventListener('DOMContentLoaded', function() {
    updateAuthButtons();
  });
</script>
<!-- 页脚 -->
<footer>
  <div class="copyright">
    <p>© 2023 探索世界旅游网 版权所有</p>
  </div>
</footer>
</body>
</html>